package wangZhong.app.dwd.log;
/**
 * @author wangz
 * @date 2022/9/1 17:32
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import wangZhong.app.BaseAppV1;
import wangZhong.common.Constant;
import wangZhong.util.AtguiguUtil;
import wangZhong.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;
import java.util.Map;

public class Dwd_01_DwdBaseLogApp extends BaseAppV1 {


    private static final String START = "start";
    private static final String DISPLAY = "display";
    private static final String ACTION = "action";
    private static final String ERR = "err";
    private static final String  PAGE = "page";

    public static void main(String[] args) {
        new Dwd_01_DwdBaseLogApp().init(
                3001,
                2,
                "Dwd_01_DwdBaseLogApp",
                Constant.TOPIC_EDU_LOG
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        SingleOutputStreamOperator<JSONObject> etledStream = etl(stream);

        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(etledStream);

        Map<String, DataStream<JSONObject>> streams = splitStream(validatedStream);

        writeToKafka(streams);

    }

    private void writeToKafka(Map<String, DataStream<JSONObject>> streams) {
        streams.get(PAGE).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGES));
        streams.get(ERR).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERRS));
        streams.get(ACTION).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTIONS));
        streams.get(START).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_STARTS));
        streams.get(DISPLAY).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAYS));

    }

    private Map<String, DataStream<JSONObject>>  splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {

        OutputTag<JSONObject> display = new OutputTag<JSONObject>("display"){};
        OutputTag<JSONObject> action1 = new OutputTag<JSONObject>("action"){};
        OutputTag<JSONObject> pages = new OutputTag<JSONObject>("page"){};
        OutputTag<JSONObject> errs = new OutputTag<JSONObject>("err"){};

        SingleOutputStreamOperator<JSONObject> startStream = validatedStream
                .process(new ProcessFunction<JSONObject, JSONObject>() {
                    @Override
                    public void processElement(JSONObject object,
                                               Context context,
                                               Collector<JSONObject> collector) throws Exception {
                        if (object.containsKey("start")) {
                            collector.collect(object);
                        }else {
                            JSONObject common = object.getJSONObject("common");
                            JSONObject page = object.getJSONObject("page");
                            Long ts = object.getLong("ts");

                            // 1. 曝光
                            JSONArray displays = object.getJSONArray("displays");
                            if (displays != null) {
                                for (int i = 0; i < displays.size(); i++) {
                                    JSONObject display1 = displays.getJSONObject(i);
                                    display1.putAll(common); // 把common中的字段复制到display中
                                    display1.putAll(page);
                                    display1.put("ts", ts);

                                    context.output(display, display1);
                                }
                                // 处理完displays之后, 应该把这个字段移除
                                object.remove("displays");
                            }


                            // 2. 活动
                            JSONArray actions = object.getJSONArray("actions");
                            if (actions != null) {
                                for (int i = 0; i < actions.size(); i++) {
                                    JSONObject action = actions.getJSONObject(i);
                                    action.putAll(common); // 把common中的字段复制到display中
                                    action.putAll(page);
                                    context.output(action1, action);

                                }
                                object.remove("actions");
                            }

                            // 3. 错误
                            if (object.containsKey("err")) {
                                context.output(errs, object);
                                object.remove("err");
                            }

                            // 4. page
                            if (page != null) {
                                context.output(pages, object);
                            }

                                }
                            }




                });
        HashMap<String, DataStream<JSONObject>> result = new HashMap<>();
        result.put(START,startStream);
        result.put(DISPLAY,startStream.getSideOutput(display));
        result.put(ACTION,startStream.getSideOutput(action1));
        result.put(ERR,startStream.getSideOutput(errs));
        result.put(PAGE,startStream.getSideOutput(pages));
        return result;
    }

    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(SingleOutputStreamOperator<JSONObject> etledStream) {
      return   etledStream
                .keyBy(object -> object.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, JSONObject>() {

                    private ValueState<String> firstvisitdatestate;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        firstvisitdatestate = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstVisitDateState",String.class));
                    }

                    @Override
                    public JSONObject map(JSONObject object) throws Exception {
                        JSONObject common = object.getJSONObject("common");

                        String fistVisit = firstvisitdatestate.value();
                        Long ts = object.getLong("ts");
                        String today = AtguiguUtil.toDate(ts);

                        if ("1".equals(common.getString("is_new"))) {
                            if (fistVisit == null) {
                                firstvisitdatestate.update(today);
                            }else if (!today.equals(fistVisit)) {
                                common.put("is_new","0");
                            }
                        }else {
                            if (firstvisitdatestate == null) {
                                String yesterday = AtguiguUtil.toDate(ts - (24 * 60 * 60 * 1000));
                                firstvisitdatestate.update(yesterday);
                            }
                        }
                        return object;



                    }
                });


    }

    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {

       return stream
                .filter(json -> {
                    try {
                        JSON.parseObject(json);
                    }catch (Exception e){
                        System.out.println("json格式有误, 请检查: " + json);
                        return false;
                    }
                    return true;
                })
                .map(JSON::parseObject);
    }
}
